import difference from 'lodash/difference';
/**
 *  转换ant table的sorter对象转换成分页的查询的排序字段
 * @param {object} sorter
 */
export const conventSorter = sorter => {
    const option = {};
    if(sorter)
        if(sorter.order && sorter.field) {
            // 点击排序
            option.sortField = sorter.field;
            if(sorter.order === 'descend') option.isDesc = true;
            else option.isDesc = false;
        } else {
            // 取消排序
            option.sortField = undefined;
            option.isDesc = undefined;
        }
    return option;
};

/**
 * 计算table的 selectedRows
 * @param {*} preKeys 上一个操作 返回的 selectedKeys
 * @param {*} preRows 上一个操作 返回的 selectedRows
 * @param {*} currentKeys 本次操作 返回的 selectedKeys
 * @param {*} currentRows 本次操作 返回的 selectedRows
 * @param {*} keyIndex eg: id
 */
export const computeSelectedRows = (preKeys, preRows, currentKeys, currentRows, keyIndex = 'id') => {
    if(currentKeys.length === 0)
        return [];
    // 勾选
    if(currentKeys.length > preKeys.length) {
        const newKeys = difference(currentKeys, preKeys);
        const newRows = [];
        newKeys.forEach(key => {
            const row = currentRows.find(r => r[keyIndex] === key);
            if(row)
                newRows.push(row);
        });
        return [...preRows, ...newRows];
    } else if(currentKeys.length < preKeys.length) { // 取消勾选
        const deleteKeys = difference(preKeys, currentKeys);
        const newRows = preRows.filter(d => !deleteKeys.includes(d[keyIndex]));
        return newRows;
    }
    return preRows;
};

export const hasPermissions = (data, name) => Array.isArray(data) && data.length > 0 && data.some(item => item === name);
export const getPrintPageUrl = (id, currentUserName) =>
    `/afterSales/print/report.html?id=${id}&currentUserName=${currentUserName}&name=ClaimSettlement&title=${encodeURI('索赔款报销审批表')}`;
export const getExportPiPageUrl = id => `/afterSales/print/report.html?id=${id}&name=ClaimSettlement&title=${encodeURI('导出PI')}`;

/**
 *  原始数据转化为支持单元格行合并的数据
 *  使用场景 清单映射清单时，主单字段单元格合并
 *  @data 原表格数据
 *  @groupByKey 合并数据的key (主单数据的Id)
 *  @rowSpanKeyList 需要合并的字段 (编号、名称、操作列等)
 */
import {groupBy} from 'lodash';
export const generateRowSpanDatas = (details, groupByKey, rowSpanKeyList) => {
    // const details = flattenData(data);
    const groupByData = groupBy(details, groupByKey);
    const result = [];
    for(const key in groupByData) {
        const array = groupByData[key];
        array.forEach((item, index) => {
            if(index === 0) {
                item.rowSpan = array.length;
                item.claimIdBak = array[0].claimId;
                result.push(item);
            } else {
                item.claimIdBak = array[0].claimId;
                rowSpanKeyList.forEach(rowSpanKey => {
                    delete item[rowSpanKey];
                });
                result.push(item);
            }
        });
    }
    return result;
};
